package org.skydiveapp;

import java.text.MessageFormat;

import org.skydiveapplibrary.ui.InterfaceManager;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.WeightUnit;
import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.ui.CalculatorTypeAdapter;
import org.skydiveapplibrary.ui.FormatUtility;

import org.skydiveapplibrary.util.CalculatorType;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class WingLoadCalculatorActivity extends SherlockActivity
{
	// data
	private float result = 0;
	private boolean isDualDisplay;
	
	// settings repository
	private SettingsRepository settingsRepository;
	
	// listeners
	private OnItemSelectedListener typeSelectedListener = new OnItemSelectedListener()
	{
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
		{
			updateUI();
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent)
		{
			updateUI();
		}
	};
	private TextWatcher textChangeListener = new TextWatcher()
	{
		@Override
		public void onTextChanged(CharSequence text, int arg1, int arg2, int arg3)
		{
			// recalculate
			calculate();
		}
		
		@Override
		public void beforeTextChanged(CharSequence text, int arg1, int arg2,
				int arg3)
		{
		}
		
		@Override
		public void afterTextChanged(Editable editable)
		{
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		settingsRepository = new SettingsRepository(this);
		
		if (settingsRepository.getUseLightTheme())
			super.setTheme(R.style.SkydiveAppTheme_Light_SemiTransparent);
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.wing_load_calculator);

		isDualDisplay = this.findViewById(R.id.phoneLayout) == null;
		
		initializeUI();
	}

	
	@Override
	public void onResume()
	{
		super.onResume();
		
		// update UI
		updateUI();
	}
	
	private void initializeUI()
	{		
		// set subtitle text
		InterfaceManager.getInstance().setSubtitleText(getSupportActionBar(), 
				getResources().getString(R.string.wing_load_calculator_label));
		
		// load type spinner
		Spinner typeSpinner = (Spinner) findViewById(R.id.WingLoadCalculateTypeSpinner);
		typeSpinner.setAdapter(new CalculatorTypeAdapter(this));
		typeSpinner.setOnItemSelectedListener(typeSelectedListener);
		
		// get weight unit
		WeightUnit weightUnit = settingsRepository.getWeightUnit();
		
		// set labels
		TextView yourWeightLabel = (TextView) findViewById(R.id.WingLoadYourWeightLabel);
		yourWeightLabel.setText(getString(R.string.wing_load_your_weight_label));
		
		TextView equipWeightLabel = (TextView) findViewById(R.id.WingLoadEquipmentWeightLabel);
		equipWeightLabel.setText(getString(R.string.wing_load_rig_weight_label));

		// add text change listeners
		EditText yourWeightField = (EditText) findViewById(R.id.WingLoadYourWeightField);
		yourWeightField.setHint(weightUnit.getResourceId());
		yourWeightField.addTextChangedListener(textChangeListener);
		
		EditText equipWeightField = (EditText) findViewById(R.id.WingLoadEquipmentWeightField);
		equipWeightField.setHint(weightUnit.getResourceId());
		equipWeightField.addTextChangedListener(textChangeListener);
		
		EditText canopySizeField = (EditText) findViewById(R.id.WingLoadCanopySizeField);
		canopySizeField.addTextChangedListener(textChangeListener);
		
		EditText wingLoadingField = (EditText) findViewById(R.id.WingLoadDesiredWingLoadingField);
		wingLoadingField.addTextChangedListener(textChangeListener);
	}
	
	private void updateUI()
	{
		// get fields
		Spinner typeSpinner = (Spinner) findViewById(R.id.WingLoadCalculateTypeSpinner);
		TableRow canopySizeRow = (TableRow) findViewById(R.id.WingLoadCanopySizeRow);
		TableRow wingLoadRow = (TableRow) findViewById(R.id.WingLoadDesiredWingLoadingRow);

		// get calculator type
		CalculatorType type = (CalculatorType)typeSpinner.getSelectedItem();
		
		// update based on selected type
		if (type == CalculatorType.WingLoading)
		{
			canopySizeRow.setVisibility(View.VISIBLE);
			wingLoadRow.setVisibility(View.GONE);
		}
		else if (type == CalculatorType.CanopySize)
		{
			canopySizeRow.setVisibility(View.GONE);
			wingLoadRow.setVisibility(View.VISIBLE);
		}
		else if (type == CalculatorType.ExtraWeight)
		{
			canopySizeRow.setVisibility(View.VISIBLE);
			wingLoadRow.setVisibility(View.VISIBLE);
		}
		
		// recalculate
		calculate();
	}
	
	private void calculate()
	{
		// get fields
		Spinner typeSpinner = (Spinner) findViewById(R.id.WingLoadCalculateTypeSpinner);
		EditText yourWeightField = (EditText) findViewById(R.id.WingLoadYourWeightField);
		EditText equipWeightField = (EditText) findViewById(R.id.WingLoadEquipmentWeightField);
		EditText canopySizeField = (EditText) findViewById(R.id.WingLoadCanopySizeField);
		EditText wingLoadingField = (EditText) findViewById(R.id.WingLoadDesiredWingLoadingField);
		TextView resultTextView = (TextView) findViewById(R.id.WingLoadResultField);

		// get calculator type
		CalculatorType type = (CalculatorType)typeSpinner.getSelectedItem();
		
		// get values
		float yourWeight = getValue(yourWeightField);		
		float equipWeight = getValue(equipWeightField);
		float canopySizeSqFt = getValue(canopySizeField);
		float wingLoadLbsSqFt = getValue(wingLoadingField);
		
		// get preferred metrics
		WeightUnit weightUnit = settingsRepository.getWeightUnit();

		// calculate result
		this.result = CalculatorType.calculate(
				type,
				yourWeight, equipWeight, weightUnit,
				canopySizeSqFt, wingLoadLbsSqFt);
		
		// get result label format
		String resultStrFormat = getString(R.string.wing_load_result_format);
		String resultUnit = "";
		if (type == CalculatorType.WingLoading)
		{
			resultUnit = getString(R.string.wing_load_unit);
		}
		else if (type == CalculatorType.CanopySize)
		{
			resultUnit = getString(R.string.area_unit_square_feet);
		}
		else if (type == CalculatorType.ExtraWeight)
		{
			resultUnit = getString(weightUnit.getResourceId());
		}
		
		// set result
		resultTextView.setText(MessageFormat.format(resultStrFormat,
				FormatUtility.toNumericString(result),
				resultUnit));
	}
	
	private float getValue(TextView textView)
	{
		String text = textView.getText().toString();
		
		if (FormatUtility.isEmptyOrNull(text))
		{
			return 0;
		}
		
		return Float.valueOf(text);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    	menu.findItem(R.id.menu_back).setVisible(isDualDisplay);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int itemId = item.getItemId();
		if (itemId == R.id.menu_back)
		{
			close();
			return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
    }
    
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
	}
}
